package com.gentlemancredit.app;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.gentlemancredit.app.base.BaseActivity;
import com.just.agentweb.AgentWeb;

import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

@EActivity(R.layout.activity_browser)
public class BrowserActivity extends BaseActivity {

    private AgentWeb mAgentWeb;

    @ViewById
    protected RelativeLayout browser_content, browser_content_error;

    @ViewById
    protected TextView head_title;

    private String url;

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        browser_content.setVisibility(View.VISIBLE);
        browser_content_error.setVisibility(View.GONE);

        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            url = extras.getString("url");
        } else {
            showToast("地址不能为空");
            finish();
            return;
        }

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(browser_content, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(mWebChromeClient)
                .createAgentWeb()
                .ready()
                .go(url);
        WebSettings webSettings = mAgentWeb.getAgentWebSettings().getWebSettings();
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowFileAccessFromFileURLs(true);

    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        mAgentWeb.clearWebCache();
        super.onDestroy();
    }

    @Override
    public void finish() {
        mAgentWeb.clearWebCache();
        super.finish();
    }


    @Click
    @Override
    public void doback() {
        boolean isBack = mAgentWeb.back();
        if (!isBack) {
            this.finish();
        }
    }

    private void notfound() {
        browser_content.setVisibility(View.GONE);
        browser_content_error.setVisibility(View.VISIBLE);
//        head_title.setText("");
    }


    @Click
    public void reload_btn() {
        mAgentWeb.getUrlLoader().reload();
        browser_content.setVisibility(View.VISIBLE);
        browser_content_error.setVisibility(View.GONE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do you  work
        }

//        @TargetApi(android.os.Build.VERSION_CODES.M)    //171016 处理404错误
//        @Override
//        public void onReceivedHttpError(WebView view, WebResourceRequest request,
//                                        WebResourceResponse errorResponse) {
//            super.onReceivedHttpError(view, request, errorResponse);
//            // 这个方法在6.0才出现
//            int statusCode = errorResponse.getStatusCode();
//            Log.e("TAG", "onReceivedError(BrowserActivity.java)statusCode=" + statusCode);
//            System.out.println("onReceivedHttpError code = " + statusCode);
//            if (404 == statusCode || 500 == statusCode) {
//                notfound();
//            }
//        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            // 断网或者网络连接超时
            int errorCode = error.getErrorCode();
            Log.e("TAG", "onReceivedError(BrowserActivity.java)errorCode=" + errorCode);
            if (errorCode == ERROR_HOST_LOOKUP || errorCode == ERROR_CONNECT || errorCode == ERROR_TIMEOUT) {
                notfound();
            }
        }


    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (title != null || title.length() != 0) {
                //todo 标题最多显示8个字
                if (title.length() > 8) {
                    String subTitle = title.substring(0, 8) + "...";
                    head_title.setText(subTitle);
                } else {
                    head_title.setText(title);
                }
            }

            Log.e("TAG", "onReceivedTitle(BrowserActivity.java)title=" + title);
            //171016 处理404错误 android 6.0 以下通过title获取
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                if (title.contains("404") || title.contains("500") || title.contains("Error")) {
                    notfound();
                }
            }

        }


    };


}
